package homevideo_model

import (
	"iptv_server/v3/src/database"
	"iptv_server/v3/src/settings"
	"path"

	"gorm.io/gorm"
)

type Home struct {
	ID   uint   `gorm:"primarykey" json:"id"`
	Name string `gorm:"type:varchar(50);" json:"name"`
	Key  string `gorm:"type:varchar(50);index:idx_sourcekey_name,unique" json:"source_name"`
	// SourceKey  string `gorm:"type:varchar(100);index:idx_sourcekey_name,unique"`
	Categorys []Category `json:"class"`
}

// type Class struct {
// 	Classes []Home `json:"classes"`
// }

// func GetHomeClasses(id uint) (cl *Class, err error) {
// 	var h *Home
// 	if h, err = GetHome(id); err != nil {
// 		return nil, err
// 	} else {
// 		hs := make([]Home, 1)
// 		hs = append(hs, *h)
// 		cl = new(Class)
// 		cl.Classes = hs
// 		return cl, nil
// 	}
// }

// 数据库操作
func GetHome(id int) (h *Home, err error) {
	h = &Home{}
	err = database.DB.Model(h).Preload("Categorys", func(db *gorm.DB) *gorm.DB {
		return database.DB.Order("id ASC")
	}).First(h, id).Error

	if err == nil && len(h.Categorys) > 0 {
		cates := make([]Category, 0)
		for i := 0; i < len(settings.NewCates_MORES); i++ {
			// 1 new 2 new2 3 push
			var name string
			if i == 0 {
				name = "✨"
			} else {
				name = "🎖️"
			}
			cates = append(cates, Category{
				ID:   0,
				Type: 2,
				Name: name,
				// Dir:    settings.NewCates_MORES[i],
				// HomeID: h.Categorys[0].HomeID,
				More: path.Join("/tv/category", settings.NewCates_MORES[i]),
			})
		}
		cates = append(cates, Category{
			ID:   0,
			Type: 2,
			Name: "_",
			// Dir:    settings.NewCates_PUSH,
			// HomeID: h.Categorys[0].HomeID,
			More: path.Join("/tv/category", settings.NewCates_PUSH),
		})
		cates = append(cates, h.Categorys...)
		h.Categorys = cates
	}
	// err = database.DB.First(h, id).Error
	return
}

// func (home *Home) GetAllCategory() (cat []Category, err error) {
// 	err = database.DB.Where("home_id = ?", home.ID).Find(&cat).Error
// 	return
// }

func GetAllHome() (hs []*Home, err error) {
	// hs := make([]*Home, 0, 16)
	err = database.DB.Find(&hs).Error
	return hs, err
}

func (h *Home) Create() (err error) {
	err = database.DB.Create(h).Error
	return
}

func (h *Home) Save() (err error) {
	err = database.DB.Save(h).Error
	return
}

// func UpdateHome(db *gorm.DB, id uint, name string, sourceKey string) error {
// 	h := &Home{
// 		name:      name,
// 		sourceKey: sourceKey,
// 	}
// 	h.ID = id
// 	r := db.Save(h)
// 	return r.Error
// }
